package com.jinkaimen.kqb.ui.activity.hss;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.ui.widget.TitleBarView;
import com.jinkaimen.kqb.R;
import com.jinkaimen.kqb.bean.ShareUrlBean;
import com.jinkaimen.kqb.manager.ApiManager;
import com.jinkaimen.kqb.utils.PermissionUtils;
import com.jinkaimen.kqb.utils.QrcodeUtils;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import retrofit2.Call;
import retrofit2.Response;


/**
 * 二维码分享
 */
public class ShareQrCodeActivity extends BaseActivity {

    private ImageView iv_qrcode;
    private RelativeLayout rl_taipai;
    private TextView mTvGoodTeacherName;
    private String url;

    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void initTitleBar() {

        mTitleBarView.setTitleText("二维码推广").addActions(new TitleBarView.Action("保存") {
            @Override
            public void performAction(View view) {
                saveImg();
            }
        }).addActions(new TitleBarView.Action("分享") {
            @Override
            public void performAction(View view) {
                UMImage image = new UMImage(ShareQrCodeActivity.this, "http://7xk9dj.com1.z0.glb.clouddn.com/refreshlayout/images/staggered11.png");//网络图片
//                UMImage image = new UMImage(ShareActivity.this, file);//本地文件
//                UMImage image = new UMImage(ShareActivity.this, R.drawable.xxx);//资源文件
//                UMImage image = new UMImage(ShareActivity.this, bitmap);//bitmap文件
//                UMImage image = new UMImage(ShareActivity.this, byte[]);//字节流
                UMImage thumb = new UMImage(ShareQrCodeActivity.this, R.mipmap.ic_launcher);
                image.setThumb(thumb);


                UMWeb web = new UMWeb(url);
                web.setTitle("个人收款神器，免费注册");//标题
                web.setThumb(thumb);  //缩略图
                web.setDescription("支持微信、支付宝、QQ，信用卡无卡快捷，银联二维码。大额秒到，还能推广赚钱");//描述


                new ShareAction(ShareQrCodeActivity.this)
                        .withText("hello").withMedia(web)
                        .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                        .setCallback(shareListener)
                        .open();
            }
        });
    }

    @Override
    protected void initIntentData(Intent callIntent) {
    }

    @Override
    protected int initContentView() {
        return R.layout.activity_share_qr_code;
    }

    @Override
    protected void initChildView() {
        rl_taipai = (RelativeLayout) findViewById(R.id.rl_activity_shop_collection_taipai);
        iv_qrcode = (ImageView) findViewById(R.id.iv_activity_shop_collection_qrcode);
        mTvGoodTeacherName = (TextView) findViewById(R.id.tv_good_teacher_name);
    }

    @Override
    protected void initChildData() {
        ApiManager.getApi().shareUrl("HSS001010").enqueue(new NetCallBack<ShareUrlBean>() {
            @Override
            protected void onSuccess(Call<ShareUrlBean> call, Response<ShareUrlBean> response) {
                ShareUrlBean shareUrlBean = response.body();
                url = shareUrlBean.shareUrl;
                mTvGoodTeacherName.setText("优秀创业导师: " + shareUrlBean.name);
                ViewGroup.LayoutParams layoutParams = iv_qrcode.getLayoutParams();
//        Bitmap bitmap = QrcodeUtils.encodeAsBitmap(qrUrl + "?code=" + code + "&sign=" + sign, layoutParams.width, layoutParams.height);
                Bitmap bitmap = QrcodeUtils.encodeAsBitmap(shareUrlBean.shareUrl, layoutParams.width, layoutParams.height);
                iv_qrcode.setImageBitmap(bitmap);
            }

            @Override
            protected void hiddenProgress() {
                hideLodingDialog();
            }
        });


    }

    @Override
    protected void setChildViewListener() {

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

            default:
                break;
        }
    }

    //保存图片到系统相册
    private void saveImg() {
        rl_taipai.buildDrawingCache();
        Bitmap bitmap = rl_taipai.getDrawingCache();
        //6.0动态申请权限
        PermissionUtils.checkPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE");
        //将Bitmap 转换成二进制，写入本地
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] byteArray = stream.toByteArray();
        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/钱包++");
        if (!dir.isFile()) {
            dir.mkdir();
        }
        File file = new File(dir, "店铺二维码.png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(byteArray, 0, byteArray.length);
            fos.flush();
            // 把文件插入到系统图库
            try {
                MediaStore.Images.Media.insertImage(getContentResolver(),
                        file.getAbsolutePath(), "店铺二维码.png", null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // 通知图库更新
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(file);
            intent.setData(uri);
            sendBroadcast(intent);
            Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        }
    }


    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(ShareQrCodeActivity.this, "成功了", Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(ShareQrCodeActivity.this, "失败" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(ShareQrCodeActivity.this, "取消了", Toast.LENGTH_LONG).show();

        }
    };
}
